const helper = require("../extend/helper");

const Service = require("egg").Service;

class AdminService extends Service {
  // admin登陆
  async adminLogin(params) {
    const { ctx, app } = this;
    const user = await ctx.model.Admin.findOne({
      userName: params.userName,
    });

    if (!user) {
      return {
        msg: "用户不存在",
        code: 100,
      };
    }
    const isMatch = await ctx.helper.comparePassword(
      params.password,
      user.password
    );

    if (!isMatch) {
      return {
        msg: "用户名或密码错误",
        code: 101,
      };
    }

    const token = app.jwt.sign({ ...user }, app.config.jwt.secret, {
      expiresIn: "24h", //token有效时间
    });
    ctx.cookies.set("token", token, {
      maxAge: 86400000,
      httpOnly: true,
    });
    return {
      code: 200,
      msg: "登陆成功",
      data: {
        token,
        userName: user.userName,
      },
    };
    // const res = await ctx.model.Admin.create(params);
    // return res;
  }

  // admin 退出登陆
  async adminLogout() {
    const { ctx } = this;
    ctx.cookies.set("token", "", {
      maxAge: 0,
    });
    return {
      msg: "退出登陆成功",
    };
  }

  async create(body) {
    const { ctx } = this;
    const hash = await helper
      .genSaltPassword(body.password)
      .then(async (hash) => {
        return hash;
      });
    const res = await ctx.model.Admin.create({
      userName: body.userName,
      password: hash,
    });
    return res;
  }

  async list() {
    const { ctx } = this;
    const res = await ctx.model.Admin.find();
    return res;
  }
  async remove(id) {
    const { ctx } = this;
    const res = await ctx.model.Admin.deleteOne({ _id: id });
    return res;
  }
  async update(body) {
    const { ctx } = this;
    body.updateTime = Date.now();
    const hash = await helper
      .genSaltPassword(body.password)
      .then(async (hash) => {
        return hash;
      });
    body.password = hash;
    ctx.model.Admin.findByIdAndUpdate(
      body.id,
      {
        ...body,
      },
      (err, res) => {
        return err ? "" : res;
      }
    );
  }
}

module.exports = AdminService;
